export default {
	//返回上一页
	navigateBack(number = 1){
		if(getCurrentPages().length>1){
			uni.navigateBack({delta: number})
		}else{
			// #ifdef H5
			window.history.go(-number)
			// #endif
			// #ifndef H5
			uni.switchTab({
			    url: '/pages/index/index'
			});
			// #endif
		}
	},
	//跳转
	navigator(url, open){
		uni[open || 'navigateTo']({
			url: url
		})
	},
	//获取导航栏高度
	getNavBarHeight(){
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		let barHeight = menuButtonInfo.height + (menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight']) * 2 + 2
		// #endif
		// #ifdef APP-PLUS || H5
		let barHeight = 44
		// #endif
		return barHeight
	},
	//获取状态栏高度
	getStatusHeight(){
		return uni.getSystemInfoSync()['statusBarHeight']
	},
	//获取状态栏+导航栏高度
	getStatusBarHeight(){
		// #ifdef MP-WEIXIN
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'] + menuButtonInfo.height + (menuButtonInfo.top - uni.getSystemInfoSync()['statusBarHeight']) * 2 + 2
		// #endif
		// #ifdef APP-PLUS || H5
		let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'] + 44
		// #endif
		return statusBarHeight
	},
	//获取头部背景高度
	getHeaderBackgroundHeight(height){
		return uni.upx2px(height) + this.getStatusBarHeight()
	},
	//获取头部背景偏移量
	getHeaderBackgroundPosition(height=176){
		// #ifndef H5
		height = 176
		// #endif
		let position = uni.upx2px(height) - this.getStatusBarHeight()
		// #ifdef H5
		position = position + 44
		// #endif
		return position > 0 ? position : 0
	},
	//px转rpx
	px2rpx(px){
		return px/(uni.upx2px(px)/px)
	},
	//图片转base64
	imgBase64(url) {
		uni.request({
			url: url,
			method: 'GET',
			responseType: 'arraybuffer',
			success: async res => {
				return 'data:image/jpeg;base64,' + wx.arrayBufferToBase64(res.data)
			}
		});
	},
	//获取时间
	parseTime(time, cFormat) {
		if (arguments.length === 0) {
			return null
		}
		const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
		let date
		if (typeof time === 'object') {
			date = time
		} else {
			if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
				time = parseInt(time)
			}
			if (typeof time === 'number' && time.toString().length === 10) {
				time = time * 1000
			}
			date = new Date(time)
		}
		const formatObj = {
			y: date.getFullYear(),
			m: date.getMonth() + 1,
			d: date.getDate(),
			h: date.getHours(),
			i: date.getMinutes(),
			s: date.getSeconds(),
			a: date.getDay()
		}
		const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
			const value = formatObj[key]
			// Note: getDay() returns 0 on Sunday
			if (key === 'a') {
				return ['日', '一', '二', '三', '四', '五', '六'][value ] 
			}
			return value.toString().padStart(2, '0')
		})
		return time_str
	},
	// 获取url参数
	getUrlParams(param, k, p) {
		if (typeof param != 'string') return {};
		k = k ? k : '&'; //整体参数分隔符
		p = p ? p : '='; //单个参数分隔符
		var value = {};
		if (param.indexOf(k) !== -1) {
			param = param.split(k);
			for (var val in param) {
				if (param[val].indexOf(p) !== -1) {
					var item = param[val].split(p);
					value[item[0]] = item[1];
				}
			}
		} else if (param.indexOf(p) !== -1) {
			var item = param.split(p);
			value[item[0]] = item[1];
		} else {
			return param;
		}
		return value;
	},
	//获取路径距离
	distance(lat1,lng1,lat2,lng2){
	    if(lat1 && lng1 && lat2 && lng2){
	      let radLat1 = this.rad(lat1);
	      let radLat2 = this.rad(lat2);
	      let a = radLat1 - radLat2;
	      let b = this.rad(lng1) - this.rad(lng2);
	      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	      s = s * 6378.137;
	      // EARTH_RADIUS;
	      s = Math.round(s * 10000) / 10000;
	      return s
	    }else{
	      return 0
	    }
	  },
	rad(d){
	    return d*Math.PI/180.0
	},
	//获取几天后日期
	getDateByDay(number){
		var date1 = new Date();
		var date2 = new Date(date1);
		date2.setDate(date1.getDate() + number);
		return date2.getFullYear() + "-" + (date2.getMonth() + 1<10?'0'+(date2.getMonth() + 1):date2.getMonth() + 1) + "-" + (date2.getDate()<10?'0'+date2.getDate():date2.getDate())
	},
	//满一万转w
	tenThousandChange(number){
		if(Number(number)<10000){
			return number
		}else{
			return (Number(number)/10000).toFixed(1)
		}
	},
	// 回显数据字典
	selectLabel(datas, value) {
		var actions = [];
		Object.keys(datas).some((key) => {
			if (datas[key].value == ('' + value)) {
				actions.push(datas[key].label);
				return true;
			}
		})
		return actions.join('');
	},
	// 回显数据字典
	selectDictLabel(datas, value) {
		var actions = [];
		Object.keys(datas).some((key) => {
			if (datas[key].dictValue == ('' + value)) {
				actions.push(datas[key].dictLabel);
				return true;
			}
		})
		return actions.join('');
	},
	// 拨打电话
	makePhoneCall(phoneNumber) {
		uni.makePhoneCall({
		    phoneNumber: phoneNumber || '15325816269'
		});
	},
	// 发送短信
	sendSms(phone,body='') {
	    // #ifdef H5
		//获取设备类型
		let platform = uni.getSystemInfoSync().platform
		window.location.href = platform === 'ios' ? `sms:/open?addresses=${phone}&body=${body}`: `sms:${phone}?body=${body}` 
	    // #endif
	    
	    // #ifdef APP-PLUS
		let message = plus.messaging.createMessage(plus.messaging.TYPE_SMS)
		message.to = [phone] //这里数组中需要是字符串,否则ios会出现空白bug
		message.body = body
		plus.messaging.sendMessage(message)
	    // #endif
	},
	// 预览图片
	previewImage(imgs,current){
		let urls = imgs?(Array.isArray(imgs)?imgs:JSON.parse(imgs).map(row=>row.url)):[]
		uni.previewImage({
			urls: urls,
			current: current
		});
	},
	// 复制剪切板
	setClipboardData(data,toast){
		uni.setClipboardData({
			data: data?.toString(),
			success: function () {
				uni.showToast({
					title: toast || '复制成功，快去粘贴吧~',
					icon: 'none'
				})
			}
		});
	},
	// 操作后后退
	handleSuccess({data,time=1200,isBack=true,func='handleQuery'}={}){
		let pages = getCurrentPages()
		let beforePage = pages[pages.length - 2]
		beforePage && beforePage.$vm && beforePage.$vm[func] && beforePage.$vm[func](data)
		if(isBack){
			setTimeout(()=>{
				this.navigateBack()
			},time)
		}
	},
	// 转千字符
	addThousandsSeparator(amount=0) {
	  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	},
	// 判断是否登录状态
	isLogin(){
		if(!uni.getStorageSync('token')){
			uni.navigateTo({
				url:'/pages/login'
			})
			return false
		}
		return true
	},
	//图片转符合安全域名路径
	downloadFilestoreImage(url) {
		return new Promise((resolve, reject) => {
			let that = this;
			uni.downloadFile({
				url: url,
				success: function(res) {
					resolve(res.tempFilePath);
				},
				fail: function(err) {
					reject(err)
				}
			});
		})
	},
	/**
	 * 用户信息分享海报
	 * @param array arr2 海报素材  1背景 0二维码
	 * @param string productName 产品名称
	 * @param function successFn 回调函数
	 * 
	 */
	async userPosterCanvas(WIDTH,HEIGHT,bgImg, codeImg, avatar, nickName, successFn) {
		bgImg = await this.downloadFilestoreImage(bgImg)
		codeImg = await this.downloadFilestoreImage(codeImg)
		if(avatar){
			avatar = await this.downloadFilestoreImage(avatar)
		}else{
			avatar = '/static/img/common/avatar.png'
		}
		const ctx = uni.createCanvasContext('inviteCanvas');
		ctx.clearRect(0, 0, 0, 0);
		ctx.fillStyle = '#fff';
		ctx.drawImage(bgImg, 0, 0, uni.upx2px(WIDTH), uni.upx2px(HEIGHT));
		ctx.drawImage(codeImg, uni.upx2px(WIDTH/2) - uni.upx2px(160), uni.upx2px(300), uni.upx2px(320), uni.upx2px(320));
		ctx.setTextAlign('left')
		ctx.setFontSize(uni.upx2px(24));
		ctx.setFillStyle('#FF3300');
		// 两种加粗方式
		// ctx.setShadow(0,0,1,'#1f1f1f')
		// ctx.font = 'normal bold '+uni.upx2px(32)+'px arial,sans-serif'
		const name = nickName.substring(0,1)+'**邀您加入我们，共赢未来～'
		const nicknameWidth = ctx.measureText(name).width;
		ctx.fillText(name, uni.upx2px(WIDTH/2) - nicknameWidth/2 + uni.upx2px(22), uni.upx2px(206));
		ctx.save();
		ctx.beginPath();
		ctx.arc(uni.upx2px(WIDTH/2) - nicknameWidth/2 - uni.upx2px(22) + uni.upx2px(36)/2,uni.upx2px(180)+uni.upx2px(36)/2, uni.upx2px(36) / 2, 0, Math.PI * 2,false);
		ctx.clip()
		ctx.drawImage(avatar, uni.upx2px(WIDTH/2) - nicknameWidth/2 - uni.upx2px(22), uni.upx2px(180), uni.upx2px(36), uni.upx2px(36));
		ctx.save();
		ctx.draw(false,setTimeout(()=>{
			uni.canvasToTempFilePath({
				canvasId: 'inviteCanvas',
				fileType: 'png',
				// quality: 1,
				destWidth: WIDTH,
				destHeight: HEIGHT,
				success: function(res) {
					uni.hideLoading();
					successFn && successFn(res.tempFilePath);
				},
				fail: function(err) {
					uni.hideLoading();
				}
			})
		},500))
	},
	isWeChat() {
		const userAgent = navigator.userAgent.toLowerCase();
		return /micromessenger/.test(userAgent);
	},
}